import 'package:flutter/material.dart';

//  通过BottomNavigationBarItem封装的底部导航栏组件

// BottomNavigationBarItem配置列表(tab配置列表)
List<BottomNavigationBarItem> barItemList = [
  const BottomNavigationBarItem(
    icon: Icon(Icons.home),
    label: "首页",
  ),
  const BottomNavigationBarItem(
    icon: Icon(Icons.search),
    label: "搜索",
  ),
  const BottomNavigationBarItem(
    icon: Icon(Icons.info),
    label: "资讯",
  ),
  const BottomNavigationBarItem(
    icon: Icon(Icons.account_circle),
    label: "我的",
  )
];

class BottomNavBarItem extends StatefulWidget {
  final ValueChanged<int>? onPageChanged;
  const BottomNavBarItem({super.key, this.onPageChanged});

  @override
  State<BottomNavBarItem> createState() => _BottomNavBarItemState();
}

class _BottomNavBarItemState extends State<BottomNavBarItem> {
  // 当前选中的tab索引
  int _selectedIndex = 0;
  // 改变tab索引
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
    // tab索引改变时触发回调
    if (widget.onPageChanged != null) {
      widget.onPageChanged!(_selectedIndex);
    }
  }

  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      items: barItemList,
      // 配置底部tab样式(固定)
      type: BottomNavigationBarType.fixed,
      // 当前选中的tab索引
      currentIndex: _selectedIndex,
      // 未选中的tab样式
      // unselectedItemColor: Colors.grey,
      // 选中的tab样式
      selectedItemColor: Colors.green,
      onTap: _onItemTapped,
    );
  }
}
